
package com.shop.cloud.live.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.feign.entity.FeignPageParam;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.annotation.Inside;
import com.shop.cloud.live.admin.service.LiveConfigService;
import com.shop.cloud.live.admin.service.LiveRoomService;
import com.shop.cloud.live.admin.socket.LiveUserWebSocketServer;
import com.shop.cloud.live.common.constant.LiveRoomStatusType;
import com.shop.cloud.live.common.constant.MsgType;
import com.shop.cloud.live.common.entity.AliLive;
import com.shop.cloud.live.common.entity.LiveConfig;
import com.shop.cloud.live.common.entity.LiveRoom;
import com.shop.cloud.live.common.util.AliLiveUtil;
import com.shop.cloud.live.common.vo.LiveMsgItemVO;
import jakarta.websocket.Session;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 直播间
 *
 * @author
 * @date 2025-01-09 10:53:37
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/liveroom")
@Tag(description = "liveroom", name = "直播间管理")
public class LiveRoomController {

    private final LiveRoomService liveRoomService;
    private final LiveConfigService liveConfigService;

    /**
     * 直播间分页列表
     *
     * @param page     分页对象
     * @param liveRoom 直播间
     * @return
     */
    @Operation(summary = "直播间分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('live:liveroom:index')")
    public R getPage(Page page, LiveRoom liveRoom) {
        return R.ok(liveRoomService.page(page, Wrappers.query(liveRoom)));
    }

    /**
     * 直播间查询
     *
     * @param id
     * @return R
     */
    @Operation(summary = "直播间查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('live:liveroom:get')")
    public R getById(@PathVariable("id") String id) {
        return R.ok(liveRoomService.getById2(id));
    }

    /**
     * 直播间新增
     *
     * @param liveRoom 直播间
     * @return R
     */
    @Operation(summary = "直播间新增")
    @SysLog("新增直播间")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('live:liveroom:add')")
    public R save(@RequestBody LiveRoom liveRoom) {
        return R.ok(liveRoomService.save2(liveRoom));
    }

    /**
     * 直播间修改
     *
     * @param liveRoom 直播间
     * @return R
     */
    @Operation(summary = "直播间修改")
    @SysLog("修改直播间")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('live:liveroom:edit')")
    public R updateById(@RequestBody LiveRoom liveRoom) {
        return R.ok(liveRoomService.updateById2(liveRoom));
    }

    /**
     * 直播间违规下线
     *
     * @param liveRoom 直播间
     * @return R
     */
    @Operation(summary = "直播间违规下线")
    @SysLog("违规下线直播间")
    @PutMapping("/offline")
    @PreAuthorize("@ato.hasAuthority('live:liveroom:edit')")
    public R offline(@RequestBody LiveRoom liveRoom) throws IOException {
        // 给当前直播间在线用户发送下线通知
        List<Session> onlineUserList = LiveUserWebSocketServer.getOnlineUserList(liveRoom.getId());
        LiveMsgItemVO liveMsgItem = new LiveMsgItemVO();
        liveMsgItem.setMsgType(MsgType.LIVE_ROOM_STATUS);
        liveMsgItem.setLiveStatus(LiveRoomStatusType.OFFLINE.value());
        if (CollUtil.isNotEmpty(onlineUserList)) {
            for (Session onlineUser : onlineUserList) {
                if (Objects.nonNull(onlineUser) && onlineUser.isOpen()) {
                    onlineUser.getBasicRemote().sendText(JSONUtil.toJsonStr(R.ok(liveMsgItem)));
                }
            }
        }
        return R.ok(liveRoomService.updateById(liveRoom));
    }

    /**
     * 直播间删除
     *
     * @param id
     * @return R
     */
    @Operation(summary = "直播间删除")
    @SysLog(value = "删除直播间")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('live:liveroom:del')")
    public R removeById(@PathVariable String id) {
        return R.ok(liveRoomService.removeById2(id));
    }

    /**
     * 获取指定直播间推流地址
     *
     * @param id
     * @return R
     */
    @Operation(summary = "获取指定直播间推流地址")
    @GetMapping("/pushurl/{id}")
    @PreAuthorize("@ato.hasAuthority('live:liveroom:get')")
    public R getPushUrl(@PathVariable String id) {
        LiveConfig liveConfig = liveConfigService.getByTenantId(TenantContextHolder.getTenantId());
        if (liveConfig == null || CommonConstants.NO.equals(liveConfig.getEnable())) {
            return R.failed("请联系管理员配置直播信息");
        }
        LiveRoom liveRoom = liveRoomService.getById(id);
        if (liveRoom == null) {
            return R.failed("无效直播间");
        }
        // 不超过256字符 支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)
        // {appName}-{roomId}-{shopId}-{userId}
        String streamName = StrUtil.format("{}-{}-{}-{}", liveConfig.getAppName(), liveRoom.getId(), liveRoom.getShopId(), liveRoom.getUserId());
        AliLive aliLive = new AliLive();
        BeanUtil.copyProperties(liveConfig, aliLive);
        String pushUrl = AliLiveUtil.getPushUrl(streamName, liveRoom.getEndTime(), aliLive);
        return R.ok(pushUrl);
    }


    /**
     * 直播间分页列表（服务间调用）
     *
     * @param page     分页对象
     * @param liveRoom 直播间
     * @return
     */
    @Operation(summary = "直播间分页列表（服务间调用）")
    @PostMapping("/inside/page")
    @Inside
    public R getPageInside(@RequestBody FeignPageParam<LiveRoom> params) {
        return R.ok(liveRoomService.page(params.getPage(), Wrappers.query(params.getEtity())));
    }

    /**
     * 直播间查询（服务间调用）
     *
     * @param id
     * @return R
     */
    @Operation(summary = "直播间查询（服务间调用）")
    @GetMapping("/inside/{id}")
    @Inside
    public R getByIdInside(@PathVariable("id") String id) {
        return R.ok(liveRoomService.getById2(id));
    }

    /**
     * 获取指定直播间播流地址（服务间调用）
     *
     * @param id
     * @param playType
     * @return
     */
    @Operation(summary = "获取指定直播间播流地址（服务间调用）")
    @GetMapping("/inside/pullurl/{id}/{playtype}")
    @Inside
    public R getPullUrlInside(@PathVariable("id") String id, @PathVariable("playtype") Integer playType) {
        LiveConfig liveConfig = liveConfigService.getByTenantId(TenantContextHolder.getTenantId());
        if (liveConfig == null || CommonConstants.NO.equals(liveConfig.getEnable())) {
            return R.failed("请联系管理员配置直播信息");
        }
        LiveRoom liveRoom = liveRoomService.getById(id);
        if (liveRoom == null) {
            return R.failed("无效直播间");
        }
        // 不超过256字符 支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)
        // {appName}-{roomId}-{shopId}-{userId}
        String streamName = StrUtil.format("{}-{}-{}-{}", liveConfig.getAppName(), liveRoom.getId(), liveRoom.getShopId(), liveRoom.getUserId());
        AliLive aliLive = new AliLive();
        BeanUtil.copyProperties(liveConfig, aliLive);
        String pullUrl = AliLiveUtil.getPullUrl(streamName, playType, liveRoom.getEndTime(), aliLive);
        return R.ok(pullUrl);
    }
}
